<template>
  <div class="pro-input-container">
    <div class="prefix-icon">
      <!-- 使用插槽进行自定义 -->
      <slot name="prefixIcon">
        <Icon v-if="prefixIcon" class="input-icon" :name="prefixIcon" />
      </slot>
    </div>
    <div class="pro-input-element">
      <input
        class="input"
        :value="modelValue"
        :type="inputType"
        :placeholder="placeholder"
        @input="emitUpdateValue($event.target)"
      />
    </div>
    <div class="suffix-icon">
      <slot name="suffixIcon">
        <Icon v-if="suffixIcon" class="input-icon" :name="suffixIcon" />
      </slot>
      <!-- 直接调用事件 给空值就可以清除 -->
      <Icon
        class="input-icon"
        v-if="clearable && modelValue"
        @click="$emit('update:modelValue', '')"
        name="clear"
      />
      <Icon
        class="input-icon"
        v-if="type == 'password'"
        @click="inputType = (inputType == 'password' ? 'text' : 'password')"
        :name="inputType == 'password' ? 'eye-show' : 'eye'"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import Icon from "./../../components/icon";
interface Props {
  type?: "text" | "password" | "textarea";
  clearable?: boolean;
  placeholder?: string;
  prefixIcon?: string;
  suffixIcon?: string;
  // 用于实现v-model的属性
  modelValue?: any;
}

const props = defineProps<Props>();

const emit = defineEmits(["update:modelValue"]);
// defineEmits<{
//     (event: 'update:modelValue', value: any): void
// }>()

const emitUpdateValue = (target: EventTarget | null) => {
  const box = target as HTMLInputElement;
  emit("update:modelValue", box.value);
};
const inputType = ref(props.type || "text");
</script>

<style lang="less">
.pro-input-container {
  border: solid 1px var(--input-border-color);
  display: flex;
  width: 100%;
  padding: 0px 10px;
  border-radius: var(--border-radius);
  font-size: 13px;

  &:hover,
  &:focus {
    border-color: var(--input-border-hover-color);
  }

  .input-icon {
    width: 22px;
    height: 22px;

    & + .input-icon {
      margin-left: 10px;
    }
  }

  .prefix-icon,
  .suffix-icon {
    line-height: var(--input-height);
    height: var(--input-height);
    display: flex;
    align-items: center;
  }

  .prefix-icon {
    margin-right: 6px;
  }

  .suffix-icon {
    margin-left: 6px;
  }

  .pro-input-element {
    flex: 1;
    line-height: var(--input-height);
    height: var(--input-height);

    .input {
      width: 100%;
      border: none;
      font-size: 12px;
      outline: none;
    }
  }
}
</style>
